<template>
  <div class="address-control">
    <div class="address-container">
      <div class="address-bar" @click="onClick">
        <!-- 无默认地址 -->
        <div v-if="!haveAddress" class="add-address">
          <i class="iconfont icon-icon_adrs t7"></i>
          <span class="ET2">{{ t('addressSelect_inform_address') }}</span>
        </div>
        <!-- 选择了地址/有默认地址 -->
        <div v-else class="address-wrapper">
          <div class="address-info ET2">
            <span>{{ address.receiver }}</span>
            <span>{{ formatPhone() }}</span>
          </div>
          <div class="address ET1">
            {{ addressTxt }}
          </div>
        </div>
        <i class="iconfont icon-zhixiang"></i>
      </div>
      <div class="address-warning ET0" v-if="invalidAddress">
        {{ addressInfo.calculate_freight_text }}
      </div>
    </div>
    <!-- 地址栏底部彩线 -->
    <div class="line-img" v-if="haveAddress"></div>
    <template v-if="openNewPop">
      <!-- 地址组件 -->
      <van-popup v-model="showPopup" id="address" :close-on-click-overlay="false" position="bottom" round :style="{ height: '70%' }" :lock-scroll="false">
        <!-- 顶部 -->
        <div class="popup-header">
          <div class="popup-header-title">{{ sheetInfo.title }}</div>
          <i class="van-icon van-icon-arrow-left van-action-sheet__left" v-show="sheetInfo.showBack"
             @click="backClick"></i>
          <i class="van-icon van-icon-cross van-action-sheet__close" @click="onClick" v-show="sheetInfo.showClose"></i>
        </div>
        <!-- 内容 -->
        <div class="popup-cont">
          <address-manage v-if="showAddressManage" :addressInfo="addressInfo" @newAddress="newAddress" @onClick="onClick"
                          @setAddressInfo="setAddressInfo"></address-manage>
          <address-edit v-if="showAddressEdit" :addressInfo="addressInfo" :selectAddressId="selectAddressId"
                        @setAddressInfo="setAddressInfo" @onClick="onClick" @getDefaultAddress="getDefaultAddress"
                        @handleAddressCallback="handleAddressCallback"></address-edit>
        </div>
      </van-popup>
    </template>
    <template v-else>
      <div class="fixed-cont"  id="address" v-if="showAddressManage || showAddressEdit">
        <!-- 顶部 -->
        <div class="popup-header">
          <div class="popup-header-title">{{ sheetInfo.title }}</div>
          <i class="van-icon van-icon-arrow-left van-action-sheet__left"
             @click="handleFixedBack"></i>
        </div>
        <div class="content-box" >
          <address-manage v-if="showAddressManage"  :addressInfo="addressInfo" @newAddress="newAddress" @onClick="fixedClose"
                          @setAddressInfo="setAddressInfo"></address-manage>
          <address-edit v-if="showAddressEdit" :haveAddress="haveAddress" :addressInfo="addressInfo" :selectAddressId="selectAddressId" @onClick="fixedClose"
                        @setAddressInfo="setAddressInfo" @getDefaultAddress="getDefaultAddress"
                        @handleAddressCallback="handleAddressCallback"></address-edit>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { isEmptyObject } from "../../utils/index";
import { getDefaultAddressInfo } from "../../fetch-data/index";
import AddressManage from "../AddressManage";
import AddressEdit from "../AddressEdit";
import { ADDRESS_HANDLE } from "../../utils/constants";
import locale from "../../../../mixins/locale";

export default {
  name: 'Address',
  props: {
    address: Object,
    isCart: {
      typeof: Boolean,
      default: false
    },
    openNewPop: {
      typeof: Boolean,
      default: true
    },
    addressInfo: {
      typeof: Object,
      default: () => ({})
    },
    invalidAddress: {
      typeof: Boolean,
      default: false
    },
  },
  mixins: [locale],
  components: {
    AddressManage,
    AddressEdit
  },
  data() {
    return {
      showPopup: false,
      sheetInfo: {
        title: '',
        showClose: true,
        showBack: false,
      },
      showAddressManage: false,
      showAddressEdit: false,
      selectAddressId: '',  // 选中的地址id
    }
  },
  computed: {
    addressTxt() {
      if (!this.address) return "";
      const { province, city, county, detail } = this.address;
      return province + city + county + detail;
    },
    haveAddress() {
      return this.address && !isEmptyObject(this.address);
    }
  },
  methods: {
    // 设置选择的地址信息
    setAddressInfo(address) {
      console.log('setAddressInfo');
      this.$emit('setAddressInfo', address);
      console.log(!this.openNewPop);
      if (!this.openNewPop){
        this.fixedClose()
      }
    },
    getDefaultAddress() {
      if (!(this.isCart && isEmptyObject(this.addressInfo))) {
        this.$emit('handleCartAddressLoaded', true);
        return;
      }
      getDefaultAddressInfo().then(data => {
        let resAddress = Array.isArray(data) || !data ? {} : data;
        this.setAddressInfo(resAddress);
      }).catch(err => {
        this.setAddressInfo({});
      }).finally(() => {
        this.$emit('handleCartAddressLoaded', true);
      });
    },
    // 收货地址数据校验
    validate() {
      return new Promise((resolve, reject) => {
        /**
         * 未填写收货地址---抛出异常
         * 显示快递地址组件 && 没有默认收获地址
         */
        if (!this.haveAddress) {
          reject({
            name: 'address',
            type: '',
            error: this.t('请先添加收货地址')
          })
        } else {
          resolve()
        }
      })
    },
    // 格式化电话号码展示
    formatPhone() {
      if (this.address?.currentArea?.nation_code === '86' || this.address?.currentArea?.nation_code === '') {
        return this.address.phone
      }
      return `${this.address?.currentArea?.nation_code}-${this.address?.phone}`
    },
    // 修改地址
    onClick() {
      if (this.haveAddress) {
        this.handlePopuoInfo('地址选择', true, false, true, false);
      } else {
        this.selectAddressId = '';
        this.handlePopuoInfo('新增地址', true, true, false, true);
      }
      this.showPopup = !this.showPopup;
    },
    // 打开地址编辑/新建
    newAddress(id) {
      this.selectAddressId = id;
      this.handlePopuoInfo(id ? '编辑地址' : '新增地址', true, true, false, true);
    },
    handlePopuoInfo(title, showClose, showBack, showAddressManage, showAddressEdit) {
      this.sheetInfo = {
        title,
        showClose,
        showBack,
      };
      this.showAddressManage = showAddressManage;
      this.showAddressEdit = showAddressEdit;
    },
    backClick() {
      this.handlePopuoInfo('地址选择', true, false, true, false);
    },
    handleFixedBack(){
      this.handlePopuoInfo('地址选择', true, false, true, false);
      this.fixedClose()
    },
    fixedClose(){
      this.showAddressManage = false;
      this.showAddressEdit = false;
      console.log(this.showAddressManage,this.showAddressEdit);
    },
    /**
     * 地址处理
     * addressInfo: 传入的地址信息
     * type: 地址处理类型 add-新增，edit-编辑，delete-删除
     */
    handleAddressCallback({addressInfo = {}, type = ADDRESS_HANDLE.ADD}) {
      switch(type) {
        case ADDRESS_HANDLE.ADD:
          this.setAddressInfo(addressInfo);
          this.openNewPop? this.onClick() : this.fixedClose();
          break;
        case ADDRESS_HANDLE.EDIT:
          this.$emit('handleAddressCallback', addressInfo);
          this.openNewPop? this.onClick() : this.fixedClose();
          break;
        case ADDRESS_HANDLE.DELETE:
          this.$emit('handleAddressCallback');
          break;
        default:
          console.err('地址处理未知类型！');
      }
    }
  },
  watch:{
    showAddressManage(val){
      if(val && !this.showAddressEdit){
        this.$parent?.handleOrderBarShow(false);
      }else{
        this.$parent?.handleOrderBarShow(true);
      }
    },
    showAddressEdit(val){
      if(val && !this.showAddressManage){
        this.$parent?.handleOrderBarShow(false);
      }else{
        this.$parent?.handleOrderBarShow(true);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../assets/styles/global.scss";
@import "../../assets/styles/common.scss";
.address-control {
  margin-bottom: 0.16rem;
  background-color: #fff;
}

.address-container {
  padding: 0.32rem;
}

.address-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .add-address {
    display: flex;
    align-items: center;

    .icon-icon_adrs {
      color: #979797;
      margin-right: 0.08rem;
    }
  }

  .address-wrapper {
    display: flex column;
    align-items: flex-start;

    .address-info {
      display: flex;
      align-items: center;
      font-weight: 500;

      span:first-child {
        display: inline-block;
        margin-right: 0.48rem;
        max-width: 3rem;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    .address {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-top: 0.16rem;
      max-width: 6.14rem;
      color: #666;
    }
  }

  .icon-tiaozhuan {
    color: #c8c8c8;
  }
}

.address-warning {
  margin-top: 0.16rem;
  color: #ff4c51;
}

.img-arrow-right {
  height: 0.3rem;
}

.line-img {
  height: 0.06rem;
  background: url("../../assets/img_adrr.png") repeat;
}

.popup-header {
  width: 100%;
  max-width: 480px;
  position: fixed;
  z-index: 1;
  top: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.24rem 0;
  background: rgba(255, 255, 255, 1);
  border-radius: 0.32rem 0.32rem 0 0;
  min-height: 0.48rem;

  .popup-header-title {
    font-weight: 600;
    line-height: 0.48rem;
  }

  .van-action-sheet__left {
    position: absolute;
    top: 0.32rem;
    left: 0.32rem;
    color: #aaaaaa;
    font-size: 0.32rem;
  }

  .van-action-sheet__close {
    position: absolute;
    top: 0.32rem;
    right: 0.32rem;
    color: #aaaaaa;
    font-size: 0.32rem;
    padding: 0 !important;
  }
}

.popup-cont {
  padding-top: 0.96rem;
}

.fixed-cont{
  position: fixed;
  box-sizing: border-box;
  z-index: 2;
  bottom: 0;
  left: 0;
  background-color: #f5f5f5;
  width: 100%;
  height: 80%;
  border-radius: 0.32rem 0.32rem 0 0;
  overflow: auto;

  .content-box{
    padding-top: 0.96rem;

  }
}
</style>